<template>
  <div class="content">
    <div class="chart-container">
      <div ref="upperChartContainer" class="upper-chart"></div>
      <div ref="lowerChartContainer" class="lower-chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import jiangxi from "@/assets/jiangxi.json";
const mapData: any = jiangxi;
const upperChartContainer = ref<HTMLElement | null>(null);
const lowerChartContainer = ref<HTMLElement | null>(null);
let upperChart: echarts.ECharts | null = null;
let lowerChart: echarts.ECharts | null = null;

onMounted(() => {
  upperChart = echarts.init(upperChartContainer.value!);
  lowerChart = echarts.init(lowerChartContainer.value!);
  initUpperChart();
  initLowerChart();
  addClickEventListener();
});

onBeforeUnmount(() => {
  if (upperChart) {
    upperChart.dispose();
    upperChart = null;
  }
  if (lowerChart) {
    lowerChart.dispose();
    lowerChart = null;
  }
});

function initUpperChart() {
  echarts.registerMap("jiangxi", mapData);

  const option: echarts.EChartsOption = {
    backgroundColor: "transparent",
    series: [
      {
        type: "map",
        map: "jiangxi",
        roam: false,
        emphasis: {
          label: {
            show: true,
          },
        },
        itemStyle: {
          areaColor: "#0e2152", // 上层地图颜色
        },
        data: [],
      },
    ],
  };

  if (upperChart) {
    upperChart.setOption(option);
  }
}

function initLowerChart() {
  echarts.registerMap("jiangxi", mapData);

  const option: echarts.EChartsOption = {
    backgroundColor: "transparent",
    title: {
      text: "地图",
      left: "center",
      textStyle: {
        color: "#000",
        fontSize: 28,
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        // const { name, center, centroid } = params;
        return `地区名称: ${params.name}<br/>ID: ${params.dataIndex}`;
      },
    },
    series: [
      {
        type: "map",
        map: "jiangxi",
        roam: false,
        emphasis: {
          label: {
            show: true,
          },
        },
        itemStyle: {
          areaColor: "#fff", // 下层地图颜色
        },
        label: {
          show: true,
        },
        data: [],
      },
    ],
  };

  if (lowerChart) {
    lowerChart.setOption(option);
  }
}

function addClickEventListener() {
  if (lowerChart) {
    lowerChart.on("click", (params: any) => {
      if (params.name) {
        console.log("点击了上层地图区域：" + params.name);
      }
    });
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 800px;
}

.upper-chart {
  width: 100%;
  height: 100vh; /* 总高度为 800 像素，上下距离为 50 像素，因此上层地图高度为 750 像素 */
}

.lower-chart {
  width: 100%;
  height: 100vh;
  transform: translateY(-101vh) translateX(-10px);
}
</style>
